package com.io.nio.mappedByteBuffer.ionio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class Test {

	/**
	 * 比较io、nio、MappedByteBuffer的性能
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		RandomAccessFile journal = new RandomAccessFile("employee.txt", "rw");
		WriteMethod method = new WriteMethod();
		long start = System.currentTimeMillis();
		for (int i = 0; i < 30000; i++) {
			Employee emp = new Employee("zhang", "sulei", 1, 2, true, "good");
			method.addRecord_IO(journal, emp);
		}
		System.out.println("Spend: "
				+ (double) (System.currentTimeMillis() - start) / 1000 + "s");

		journal = new RandomAccessFile("employee2.txt", "rw");
		FileChannel channel = journal.getChannel();
		ByteBuffer data = ByteBuffer.allocate(1000);
		start = System.currentTimeMillis();
		for (int i = 0; i < 30000; i++) {
			Employee emp = new Employee("zhang", "sulei", 1, 2, true, "good");
			method.addRecord_NIO(channel, data, emp);
		}
		System.out.println("Spend: "
				+ (double) (System.currentTimeMillis() - start) / 1000 + "s");

		journal = new RandomAccessFile("employee3.txt", "rw");
		channel = journal.getChannel();
		MappedByteBuffer mbb = channel.map(FileChannel.MapMode.READ_WRITE, 0,
				2 * 1024 * 1024);
		start = System.currentTimeMillis();
		for (int i = 0; i < 30000; i++) {
			Employee emp = new Employee("zhang", "sulei", 1, 2, true, "good");
			method.addRecord_MBB(mbb, emp);
		}
		System.out.println("Spend: "
				+ (double) (System.currentTimeMillis() - start) / 1000 + "s");
	}

}
